import { useState, useImperativeHandle, forwardRef } from 'react'
import { Overlay, Menu } from '@alifd/next'
import styles from './index.module.scss'

const { Item } = Menu

const RightClickMenu = ({ back, forward }, ref) => {
  const [overlayVisible, setOverlayVisible] = useState(false)
  const [overlayOffset, setOverlayOffset] = useState([0, 0])

  useImperativeHandle(
    ref,
    () => ({
      setOverlayVisible: arg => {
        if (arg === false) {
          setOverlayVisible(false)
        } else if (arg) {
          setOverlayVisible(true)
        } else {
          setOverlayVisible(!overlayVisible)
        }
      },
      setOverlayOffset: ([x, y]) => {
        y = y + 74
        if (document.body.clientWidth - x < 200 || document.body.clientWidth - x === 200) {
          x = document.body.clientWidth - 201
        }
        if (document.body.clientHeight - y < 1) {
          y = document.body.clientHeight - 1
        }
        setOverlayOffset([x, y])
      }
    }),
    [setOverlayVisible, setOverlayOffset, overlayVisible]
  )

  return (
    <Overlay visible={overlayVisible} target={document.body} offset={overlayOffset} animation={false}>
      <Menu className={styles.menu} mode="popup" popupAlign="outside">
        <Item key="1" onClick={back}>
          撤消
        </Item>
        <Item key="2" onClick={forward}>
          重做
        </Item>
      </Menu>
    </Overlay>
  )
}

export default forwardRef(RightClickMenu)
